<script setup>
import {reactive, ref, watch} from "vue"

const urlPattern = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/ig

/**
 *
 * @type {Ref<FormInstance>}
 */
const submitRef = ref(null)
const props = defineProps({
  visible: Boolean,
  defaultData: {
    type: Object,
    default: () => {
      return {
        url: '',
        name: ''
      }
    }
  }
})

const data = reactive({
  url: '',
  name: ''
})

watch(() => props.defaultData, (value) => {
  const {url, name} = value
  data.url = url
  data.name = name
}, {deep: true})

const rules = {
  url: [
    {pattern: urlPattern, message: '链接格式不正确', trigger: 'blur'}
  ]
}

const emits = defineEmits(['update:visible', 'insertLink'])

const handleClose = () => {
  emits('update:visible', false)
}

const handleSubmit = async () => {
  const valid = await submitRef.value.validate(valid => valid)
  if (!valid) return
  const res = {...data}
  emits("insertLink", res)
  handleClose()
}
</script>

<template>
  <el-dialog
      title="超链接"
      :model-value="visible"
      show-close
      :append-to-body="true"
      @close="handleClose"
      :width="500"
  >
    <el-form :model="data" :rules="rules" label-width="100" ref="submitRef">
      <el-form-item prop="url" label="链接：">
        <el-input type="text" v-model="data.url" placeholder="https://xxxx.com/" maxlength="200" clearable/>
      </el-form-item>
      <el-form-item prop="name" label="名称：">
        <el-input type="text" v-model="data.name" placeholder="输入链接名称" maxlength="100" clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>